package indi.juzhuohan.chatroom.server;

import java.io.IOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import indi.juzhuohan.chatroom.constants.Constants;
import indi.juzhuohan.chatroom.entity.ServerInfoBean;

/**
 * 服务器启动入口
 * 
 * @author 鞠卓瀚
 */
public class ChatServer {

	Serverframe serverframe;
	static Map<String, Socket> userSocketMap = new HashMap<>();

	public ChatServer() {
		try {
//			建立服务器的Socket监听
			ServerSocket sso = new ServerSocket(Constants.SERVER_PORT);
//			打开服务器界面
			serverframe = new Serverframe();

			ServerInfoBean serverIP = getServerIP();
			loadServerInfo(serverIP);
//			循环是为了解决多客户端使用
			while (true) {
//				等待连接，阻塞实现，会得到一个客户端的连接
				Socket socket = sso.accept();
				ServerHandler serverHandler = new ServerHandler(socket, serverframe);
				serverHandler.start();
			}
		} catch (IOException e) {
			System.out.println("chatserver1");
		}
	}

	/**
	 * 获取服务器的主机名和IP地址
	 * 
	 * @return 返回服务器IP等信息
	 */
	public ServerInfoBean getServerIP() {
		ServerInfoBean sib = null;
		try {
			InetAddress serverAddress = InetAddress.getLocalHost();
			byte[] ipAddress = serverAddress.getAddress();
			sib = new ServerInfoBean();
			sib.setIp(serverAddress.getHostAddress());
			sib.setHostName(serverAddress.getHostName());
			sib.setPort(Constants.SERVER_PORT);
		} catch (Exception e) {
			System.out.println("###Cound not get Server IP." + e);
		}
		return sib;
	}

	/**
	 * 初始化加载服务器参数
	 * 
	 * @param serverInfo
	 */
	public void loadServerInfo(ServerInfoBean serverInfo) {
		serverframe.serverUI.txtIP.setText(serverInfo.getIp());
		serverframe.serverUI.txtServerName.setText(serverInfo.getHostName());
		serverframe.onlineuserpanel.txtIP.setText(serverInfo.getIp());
		serverframe.onlineuserpanel.txtServerName.setText(serverInfo.getHostName());
		serverframe.serverUI.txtLog.setText("服务器已经启动...");
	}

	public static void main(String[] args) {
		new ChatServer();
	}

}
